package com.styytech.dadabao.utils;


import java.io.File;
import java.io.FileInputStream;
import java.security.KeyStore;

import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;

import android.content.Context;


public class Snippet {

	public static final int HTTP_PORT = 80;
	public static final int HTTPS_PORT =443;
	public static final int TIME_OUT = 10000;

	public static SSLSocketFactory newSSLSocketFactory(Context context) throws Exception{
		try {
//			final String keyStorPath=CommonString.keyStoreDirectory()+CommonString.myKeystoreName;
			final String keyStorPath = "";
			//证书地址
			if(!new File(keyStorPath).exists()){;
			return null;
			}
            FileInputStream fin = new FileInputStream(keyStorPath); 

            
			
			KeyStore trusted = KeyStore.getInstance("BKS");
			try{
				trusted.load(fin, "mysecret".toCharArray());//mysecret 密码
			}finally{
				fin.close();
			}
			SSLSocketFactory sf = new SSLSocketFactory(trusted);
			sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
			return sf;
		} catch (Exception e) {
			throw e;
		}
	}
	
	public static HttpClient getHttpClient(Context context) {
		try {
			SSLSocketFactory sf = newSSLSocketFactory(context);
			
			HttpParams params = new BasicHttpParams();

			HttpConnectionParams.setConnectionTimeout(params, 10000);
			HttpConnectionParams.setSoTimeout(params, 10000);

			HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
			HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

			SchemeRegistry registry = new SchemeRegistry();
			registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), HTTP_PORT));
			registry.register(new Scheme("https", sf, HTTPS_PORT));

			ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

			// Set the default socket timeout (SO_TIMEOUT) // in
			// milliseconds which is the timeout for waiting for data.
			HttpConnectionParams.setConnectionTimeout(params, TIME_OUT);
			HttpConnectionParams.setSoTimeout(params, TIME_OUT);
			
			HttpClient client = new DefaultHttpClient(ccm, params);
			return client;
		} catch (Exception e) {
			return new DefaultHttpClient();
		}
	}
}
